package com.galaxy.order.consumer;


import com.alibaba.fastjson.JSON;
import com.galaxy.common.mq.config.RabbitConfig;
import com.galaxy.order.domain.Order;
import com.galaxy.order.domain.bo.OrderBo;
import com.galaxy.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Slf4j
@Component
public class OrderConsumer {

    @Autowired
    private OrderService orderService;

    // 消费订单创建的消息
    @RabbitListener(queues = RabbitConfig.QUEUE_ORDER_CREATE_NAME)
    public void receive(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receive message: {}", message);
        try {
            OrderBo orderBo = JSON.parseObject(message, OrderBo.class);
            Order order = orderService.insertByBo(orderBo);
            if (order != null) {
                log.info("insert order success");
                // 手动确认消息，第二个参数为multiple，表示是否批量确认
                channel.basicAck(deliveryTag, false);
            } else {
                log.error("insert order fail, message: {}", message);
                // 拒绝消息，第二个参数为requeue，表示是否重新入队
                channel.basicReject(deliveryTag, false);
            }
        } catch (Exception e) {
            log.error("处理订单消息失败, message: {}", message, e);
            try {
                // 发生异常时拒绝消息，可以选择是否重新入队
                channel.basicReject(deliveryTag, false);
            } catch (IOException ioException) {
                log.error("拒绝消息失败", ioException);
            }
        }
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); // 手动确认模式
        return factory;
    }
}
